﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace LWrap.FileParsers
{
    public class PDFFileParser:FileParserBase
    {
        private PRTokeniser _token = null;
        private PRTokeniser.TokType _tknType;
        private string _tknValue = string.Empty;

        public override string ExtractText(string filePath)
        {
            PdfReader reader = new PdfReader(filePath);
            StringBuilder sb = new StringBuilder();
            string docText = string.Empty;
            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                sb.Append(ExtractTextFromBytes(reader.GetPageContent(page)));
            }
            reader.Close();
            return sb.ToString();
        }

        private string ExtractTextFromBytes(byte[] input)
        {
            StringBuilder sb = new StringBuilder();
            _token = new PRTokeniser(input);
            while (_token.NextToken())
            {
                _tknType = _token.TokenType;
                _tknValue = _token.StringValue;
                if (_tknType == PRTokeniser.TokType.STRING)
                {
                    sb.Append(_token.StringValue);
                }
                else if ((_tknType == PRTokeniser.TokType.NUMBER) && (_tknValue == "-600"))
                {
                    sb.Append(" ");
                }
                else if ((_tknType == PRTokeniser.TokType.OTHER) && (_tknValue == "TJ"))
                {
                    sb.Append(" ");
                }
            }
            return sb.ToString();
        }
    }
}
